import { Body, Controller, Get, Post, Res, HttpStatus, UploadedFile, UseInterceptors, HttpException, Query, Request, Response, Header, All } from '@nestjs/common';
import { Video } from './video.entity';
import { VideoService } from './video.service';
import { User } from '../user/user.entity';
import utils from '../../common/utils'
import {
  apibefore
} from '../../router'
import {
  secretId,
  secretKey,
  video_SubAppId,
  video_VideoTimeout,
  video_RefererKey,
  video_SubAppId_List,
  wx_appid,
  system_wx_user,
} from '../../setting'
import axios from 'axios'

import { ValidUniqueLoginInterceptor } from 'src/interceptor/validUniqueLogin';
import { VideoServiceManager } from './video.service.manager';
import { UserService } from '../user/user.service';
import { RedisInstance } from '../../common/redis';
import { OriginalEnum, VideoEnum } from './video.enum';
const redis_editMedia = RedisInstance.initRedis();
const mp4tohls = 'mp4tohls:'
const pullvideo = 'pullvideo:'

const tencentcloud = require("tencentcloud-sdk-nodejs");
const clientConfig = {
  credential: {
    secretId: secretId,
    secretKey: secretKey,
  },
  region: "",
  profile: {
    httpProfile: {
      endpoint: "vod.tencentcloudapi.com",
    },
  },
};
const VodClient = tencentcloud.vod.v20180717.Client;
import { WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { Redis } from 'ioredis';
import { InjectRedis } from '@nestjs-modules/ioredis';
import { WsMediaEdit } from '../ws/ws.mediaedit';


@Controller(apibefore('/video_manager'))
export class VideoControllerManager {
  constructor(private readonly videoServiceManager: VideoServiceManager,
    private readonly videoService: VideoService,
    private readonly userServices: UserService,
    @InjectRedis() private readonly redis: Redis,
    private readonly wsMediaEdit: WsMediaEdit,
  ) { }
  @WebSocketServer() server;

  @Get('/findQuestionNotAnswer')
  async findQuestionNotAnswer(@Query() data, @Request() req) {
    let token: number = req.headers.token
    //查询用户的wx_user
    let findUser: User = await this.userServices.findOne(token)
    if (!findUser) {
      return new HttpException('用户不存在', HttpStatus.INTERNAL_SERVER_ERROR)
    }
    let { skip, take } = utils.getLimit(data.pageSize, data.pageIndex)
    let result = await this.videoServiceManager.findQuestionNotAnswer(skip, take, data.video_id, data.selectType)
    let sendData = {
      dataList: result.dataList || [],
      total: result.total || 0
    }

    sendData.dataList.filter(e => e.video_url || e.video_url_source).map(e => {
      e.video_url = e.video_url_source || e.video_url
      utils.getPlayVideoUrl(e)
    })
    return sendData
  }

  @Post('/validAuth')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async validAuth(@Body() videoParam, @Request() req) {
    return true
  }

  @Post('/acceptWorks')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async acceptWorks(@Body() videoParam: { id: number }) {
    let videoItem: Video = await this.videoService.findOne(videoParam.id)
    if (!videoItem) {
      return new HttpException('视频不存在', HttpStatus.INTERNAL_SERVER_ERROR)
    } else if (!videoItem.ic_group && videoItem.original == OriginalEnum.yes) {
      return new HttpException('没有关联网红', HttpStatus.INTERNAL_SERVER_ERROR)
    } else {
      let result
      if (videoItem.video_url_source || videoItem.type === VideoEnum.image) {
        result = await this.videoServiceManager.acceptWorks(videoParam.id)
      } else {
        await redis_editMedia.set(mp4tohls + videoItem.id, videoItem.id)
      }
      if (result) {
        return new HttpException(result, HttpStatus.INTERNAL_SERVER_ERROR)
      } else {
        return true
      }
    }
  }

  @Post('/convertHls')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async convertHls(@Body() videoParam: { id: number }) {
    let videoItem: Video = await this.videoService.findOne(videoParam.id)
    if (!videoItem) {
      return new HttpException('视频不存在', HttpStatus.INTERNAL_SERVER_ERROR)
    } else {
      let result
      if (!(videoItem.video_url_source || videoItem.type === VideoEnum.image)) {
        await redis_editMedia.set(mp4tohls + videoItem.id, videoItem.id)
      }
      if (result) {
        return new HttpException(result, HttpStatus.INTERNAL_SERVER_ERROR)
      } else {
        return true
      }
    }
  }


  @Post('/rejectWorks')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  rejectWorks(@Body() videoParam: { id: number, reject_reason: number }) {
    return this.videoServiceManager.rejectWorks(videoParam.id, videoParam.reject_reason)
  }


  /**
   * 提问视频关联网红
   * @param videoParam 
   */
  @Post('/changeIcGroup_question')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async changeIcGroup_question(@Body() videoParam) {
    let err = await this.videoServiceManager.changeIcGroup_question(videoParam.id, videoParam.ic_group)
    if (err) {
      return new HttpException(err, HttpStatus.INTERNAL_SERVER_ERROR)
    } else {
      return true
    }
  }

  @Post('/clearIcGroup')
  clearIcGroup(@Body() params) {
    return this.videoServiceManager.clearIcGroup(params.id)
  }

  /**
   * 复制视频到全部
   * @param data 
   * @param req 
   * @returns 
   */
  @Post('/copyToAll')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async copyToAll(@Body() data, @Request() req) {
    let result = await this.videoServiceManager.copyToAll(data.video_id)
    if (result.raw.insertId) {
      let video_id = result.raw.insertId
      await redis_editMedia.set(pullvideo + video_id, video_id)
      return true
    } else {
      return new HttpException('复制失败', HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }


  /**
   * 删除云点播资源
   * @param FileId
   * @param then
   * @param catchF
   */
  deleteVideo(FileId: string) {
    const client = new VodClient(clientConfig);
    const params = {
      "FileId": FileId,
      "SubAppId": video_SubAppId
    };
    return client.DeleteMedia(params)
  }

  @Post('/removeManager')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async removeManager(@Body() data) {
    let findVideo = await this.videoService.findOne(data.id)
    if (findVideo.source == 2) {
      return new HttpException('我后台里的视频不可删除！', HttpStatus.INTERNAL_SERVER_ERROR)
    }
    let err = await this.videoServiceManager.removeManager(data.id)
    if (err) {
      return new HttpException('删除失败，' + err, HttpStatus.INTERNAL_SERVER_ERROR)
    } else {
      // return true
      return new Promise((resolve, reject) => {
        this.deleteVideo(findVideo.video_id).then(res => {
          resolve(true)
        }).catch(err => {
          resolve(true)
        })
      })
    }
  }

  @Get('/questionWaitIsHomeList')
  async questionWaitIsHomeList(@Query() params) {
    let { skip, take } = utils.getLimit(params.pageSize, params.pageIndex)
    let result = await this.videoServiceManager.questionWaitIsHomeList(params.video_id, skip, take)
    result.data.filter(e => e.video_url || e.video_url_source).map(e => {
      e.video_url = e.video_url_source || e.video_url
      utils.getPlayVideoUrl(e)
    })
    return result
  }


  @Post('/resetQuestion')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async resetQuestion(@Body() data) {
    let err = await this.videoServiceManager.resetQuestion(data.id)
    if (err) {
      return new HttpException('取消失败，' + err, HttpStatus.INTERNAL_SERVER_ERROR)
    }
    return true
  }

  @Post('/checkNoAll')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  checkNoAll(@Body() data) {
    return this.videoServiceManager.checkNoAll(data.ic_group)
  }


  @Get('/getVideoCovers')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async getVideoCovers(@Query() data) {
    let video = await this.videoService.findOne(data.id)
    if (video) {
      let rdsk = 'video_cover:' + video.video_id
      let res: any = await this.redis.get(rdsk)
      if (res && utils.isJSON(res)) {
        res = JSON.parse(res)
      }
      if (res && res.progress == 100) {
        return res
      } else {
        let url = video.video_url_source ? video.video_url_source : video.video_url
        let item = { video_url: url }
        utils.getPlayVideoUrl(item)
        await this.redis.set(rdsk, JSON.stringify({ progress: 20 }))
        utils.GetVideoCovers(item.video_url, video.video_id, this.redis)
        return { video_id: video.video_id, progress: 20 }
      }
    } else {
      return new HttpException('视频不存在，请重试', HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }

  @Get('/getVideoCoversProgress')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async getVideoCoversProgress(@Query() data) {
    let res = await this.redis.get('video_cover:' + data.video_id)
    if (res && utils.isJSON(res)) {
      return JSON.parse(res)
    } else {
      return new HttpException('处理任务不存在，请重新点击替换', HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }

  async imageToBase64(url) {
    try {
      // 使用axios获取图片的buffer数据
      const response = await axios.get(url, { responseType: 'arraybuffer' });
      // 将buffer转换为base64字符串
      const imageBase64 = Buffer.from(response.data, 'binary').toString('base64');
      //调用媒体处理服务上传缩略图
      let result: any = await this.wsMediaEdit.batchShareCoverAndUpload(url)
      console.log(result, '调用媒体处理服务上传缩略图')
      let data: any = {
        imageBase64: imageBase64,
      }
      if (result.code === 0 || result.code?.[0] === 0) {
        data.shareCover = result.data
        return data
      } else {
        return null
      }
    } catch (error) {
      console.error(`Error fetching image at ${url}:`, error);
      return null;
    }
  }

  @Post('/replaceVideoCover')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async replaceVideoCover(@Body() data) {
    let id = data.id
    let video_id = data.video_id
    let img = await this.imageToBase64(data.img)
    if (img) {
      let err = await this.videoServiceManager.replaceVideoCover(id, video_id, img.imageBase64, img.shareCover)
      if (err) {
        return new HttpException('图片解析错误' + err, HttpStatus.INTERNAL_SERVER_ERROR)
      } else {
        return data.img
      }
    } else {
      return new HttpException('图片解析错误', HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }

  @Post('/updateInLevel3')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async updateInLevel3(@Body() data) {
    let in_level3 = data.in_level3
    let video_id = data.id
    let err = await this.videoServiceManager.updateInLevel3(video_id, in_level3)
    if (err) {
      return new HttpException(err, HttpStatus.INTERNAL_SERVER_ERROR)
    } else {
      return true
    }
  }

  @Post('/questionRewardTitleChange')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async questionRewardTitleChange(@Body() data) {
    let question_reward_title = data.question_reward_title
    let video_id = data.id
    return this.videoServiceManager.questionRewardTitleChange(video_id, question_reward_title)
  }

  @Post('/convertHLS')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async convertHLS(@Body() data) {
    let video_id = data.id
    return await this.redis.set(mp4tohls + video_id, video_id)
  }

  @Post('/moveAbroad')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async moveAbroad(@Body() data) {
    let err = await this.videoServiceManager.moveAbroad(data.id)
    if (err) {
      return new HttpException(err, HttpStatus.INTERNAL_SERVER_ERROR)
    } else {
      return true
    }
  }

}
